//引入路由插件
import VueRouter from 'vue-router';
import navsData from "@/navsData";
import getRequest from "@/Network/axios";

// import {Message} from "element-ui";

//解决重复导航报错
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}


let childrens = []
for (let i = 0; i < navsData.length; i++){
    if (!navsData[i].children){
        childrens.push(navsData[i])
    }
    if (navsData[i].children){
        for (let j = 0; j < navsData[i].children.length; j++){
            childrens.push(navsData[i].children[j])
        }
    }
}


//创建并暴露路由
const Router = new VueRouter({
    mode: 'history',
    routes: [
        //后台管理组件路由
        {
            name: 'IsContainer',
            path: '/',
            component: () => import("@/view/IsContainer"),
            redirect: '/IsHome',
            children: childrens
        },
        //登入组件路由
        {
            name: 'IsEnter',
            path: '/IsEnter',
            component: () => import('@/LoginPage/IsEnter'),
        },
        //注册组件路由
        {
            name: 'IsRegister',
            path: '/IsRegister',
            component: () => import('@/LoginPage/IsRegister'),
        },
        //404组件路由
        {
            name: 'IsError',
            path: '/IsError',
            component: () => import('@/404Page/IsError'),
        }
    ]
})


// 用户未登入的路由守卫
Router.beforeEach((to, form, next) => {
    if(!localStorage.getItem('username') &&!localStorage.getItem('token') && to.name !== 'IsEnter' && to.name !== 'IsRegister'){
        next({
            name:"IsEnter"
        })
    }else{
        next()
        // 获取当前用户信息
        getRequest({
            method: 'post',
            url: '/getUser',
            data: {
                username: localStorage.getItem('username')
            },
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        }).then(res => {

            if (res.data.status >= 400) {
                return
            }

            if (to.meta.isAuto === true && res.data.user.usertype === '0'){
                next({
                    name: 'IsError'
                })
            } else {
                next()
            }

        }).catch(err => {
            console.log(err)
        })
    }
})




//暴露路由器
export default Router;